#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017-2020 Richard Hull and contributors
# See LICENSE.rst for details.
# PYTHON_ARGCOMPLETE_OK

"""
Displays an animated gif.
"""
import os
import sys
import time
from datetime import datetime
from pathlib import Path 
from PIL import Image, ImageDraw, ImageFont 
from luma.lcd.device import pcd8544, st7735, st7789, st7567, uc1701x, ili9341, ili9486, hd44780
from luma.core.interface.serial import i2c, spi
import psutil 
#=======================================================================================


def bytes2human(n):
    """
    >>> bytes2human(10000)
    '9K'
    >>> bytes2human(100001221)
    '95M'
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.0f' % (value)       
    return "%sB" % n

  #---------------------------------------------------------------------------------------

def bytes2human2(n):
    """
    >>> bytes2human(10000)
    '9K'
    >>> bytes2human(100001221)
    '95M'
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.1f%s' % (value, s)   
    return "%s B" % n

#======================================================================================
# 

def today_date():
    # load average, uptime
       
    now = datetime.now()
    today_date = now.strftime("%Y-%m-%d")
    return "%s" \
        % (today_date)


def today_time():
    # load average, uptime
       
    now = datetime.now()
    today_time = now.strftime("%H:%M:%S")
    return "%s" \
        % (today_time)


def today_week():
    # load average, uptime
       
    now = datetime.now()
    today_week = now.strftime("%a")
    if today_week == 'Mon': w ="周一"
    elif today_week == 'Tue': w ="周二"
    elif today_week == 'Wed': w ="周三"
    elif today_week == 'Thu': w ="周四"    
    elif today_week == 'Fri': w ="周五"    
    elif today_week == 'Sat': w ="周六"    
    elif today_week == 'Sun': w ="周日"
    
    return "%s" \
        % (w)





#======================================================================================
# 

def cpu():
    cpu = psutil.cpu_percent(interval=None)
    return "%.0f%%" \
        % (cpu)

#======================================================================================
# 
         
def cpu_temp():
    if not hasattr(psutil, "sensors_temperatures"):
        sys.exit("platform not supported")
    temps = psutil.sensors_temperatures()
    if not temps:
        sys.exit("can't read any temperature")
    for name, entries in temps.items():
        for entry in entries:
            return "%.0f°C" \
            % (entry.current)

#======================================================================================
# 

def ram_total():
    rt = psutil.virtual_memory()
    return "共: %s" \
        % (bytes2human2(rt.total))

def ram_used():
    ru = psutil.virtual_memory()
    return "%s" \
        % (bytes2human2(ru.used))

def ram_free():
    rf = psutil.virtual_memory()
    return "余: %s" \
        % (bytes2human2(rf.total - rf.used))                

def ram_perc():
    rp = psutil.virtual_memory()
    return "%.0f%%" \
        % (rp.percent)


#======================================================================================
# 

def disk_total(dir):
    dt = psutil.disk_usage(dir)
    return "共: %s" \
        % (bytes2human2(dt.total))

def disk_used(dir):
    du = psutil.disk_usage(dir)
    return "%s" \
        % (bytes2human2(du.used))

def disk_free(dir):
    df = psutil.disk_usage(dir)
    return "余: %s" \
        % (bytes2human2(df.free))                

def disk_perc(dir):
    dp = psutil.disk_usage(dir)
    return "%.0f%%" \
        % (dp.percent)
#======================================================================================

def network(iface):
    stat = psutil.net_if_addrs()[iface][0]
    return "IP : %s" % \
           (stat.address)
#==========================================================================================

#=========================================================================================




#==========================================================================================
# 

def main():
  #----------------------------------------------------------------------------------
  # 
    font_pathCN = str(Path(__file__).resolve().parent.joinpath('../fonts', 'msyh.ttf'))
    font_pathEN = str(Path(__file__).resolve().parent.joinpath('../fonts', 'arial.ttf'))
    
    # 
    fontC09 = ImageFont.truetype(font_pathCN, 9)
    fontC10 = ImageFont.truetype(font_pathCN, 10)
    fontC11 = ImageFont.truetype(font_pathCN, 11)
    fontC12 = ImageFont.truetype(font_pathCN, 12)
    fontC13 = ImageFont.truetype(font_pathCN, 13)
    fontC14 = ImageFont.truetype(font_pathCN, 14)
    fontC15 = ImageFont.truetype(font_pathCN, 15)

    # 
    fontE09 = ImageFont.truetype(font_pathEN, 9)
    fontE10 = ImageFont.truetype(font_pathEN, 10)
    fontE11 = ImageFont.truetype(font_pathEN, 11)
    fontE12 = ImageFont.truetype(font_pathEN, 12)
    fontE13 = ImageFont.truetype(font_pathEN, 13)
    fontE14 = ImageFont.truetype(font_pathEN, 14)
    fontE15 = ImageFont.truetype(font_pathEN, 15)


  #--------------------------------------------------------------------------------
  # 

    cL = 69                
    cT = 36                

    CpuH = 30               
    CpuW = 6                
    CpuB = CpuH + cT       

  # 
    c0L = cL + 5           
    c1L = c0L + 16        
    c2L = c1L + 16        
    c3L = c2L + 16
    c4L = c3L + 16
  # 
    c0T = cT              
    c1T = c0T + 8           
    c2T = c1T              
    c3T = c1T
    c4T = c1T 

    c0 = psutil.cpu_percent(interval=None)
    c0BarH = int(CpuH * c0 / 100)

    c1,c2,c3,c4 = psutil.cpu_percent(interval=None, percpu=True)
    c1BarH = int((CpuH-8) * c1 / 100)
    c2BarH = int((CpuH-8) * c2 / 100)
    c3BarH = int((CpuH-8) * c3 / 100)
    c4BarH = int((CpuH-8) * c4 / 100)

  #--------------------------------------------------------------------------------
  # 
    rL = 6
    rT = 105 
    RamH = 4
    RamW = 64 
    ramTotal = psutil.virtual_memory()[0]  
    ramUsed = psutil.virtual_memory()[3]                                   
    ramFree = psutil.virtual_memory()[0] -  psutil.virtual_memory()[3]     
    ramPerc = psutil.virtual_memory()[3] / psutil.virtual_memory()[0] *100  
    rBarW = RamW * ramPerc / 100


  #--------------------------------------------------------------------------------  
  # 
    dL = 88
    dT = 105 
    DiskH = 4
    DiskW = 64 
    diskTotal = psutil.disk_usage('/')[0]  
    diskUsed = psutil.disk_usage('/')[1]  
    diskFree = psutil.disk_usage('/')[2]  
    diskPerc = psutil.disk_usage('/')[3]  
    dBarW = DiskW * diskPerc / 100

  #--------------------------------------------------------------------------------
  # 
    img_path1 = str(Path(__file__).resolve().parent.joinpath('../images', 'tytion.png'))
    img_path2 = str(Path(__file__).resolve().parent.joinpath('../images', 'cpu.png'))
    img_path3 = str(Path(__file__).resolve().parent.joinpath('../images', 'ram.png'))
    img_path4 = str(Path(__file__).resolve().parent.joinpath('../images', 'disk.png'))
    
  
    img1 = Image.open(img_path1)
    img2 = Image.open(img_path2)
    img3 = Image.open(img_path3)
    img4 = Image.open(img_path4)
    posn1 = (2,-12) 
    posn2 = (9,22)
    posn3 = (3,70)
    posn4 = (86,74)

   
    posncpu = (23,31)
    posndisk_f = (110,73)
    posndisk_t = (110,87)
    posnram_f = (26,73)
    posnram_t = (26,87)

  #------------------------------------------------------------------------------------------    
    
    bg = Image.new(device.mode, device.size, "black")
    bg.paste(img1.resize((64,42)), posn1)
    bg.paste(img2, posn2) 
    bg.paste(img3.resize((22,34)), posn3) 
    bg.paste(img4.resize((21,26)), posn4) 
    draw = ImageDraw.Draw(bg) 
  
  
  #------------------------------------------------------------------------------------------
 
    draw.rounded_rectangle((3,18,62,68), radius=8, outline="white",width = 1) 
    draw.rounded_rectangle((58,31,155,68), radius=6, outline="white",width = 1) 
    draw.rounded_rectangle((59,32,154,67), radius=6, fill="black") # CPU
    draw.rounded_rectangle((0,71,77,115), radius=6, outline="white",width = 1) 
    draw.rounded_rectangle((82,71,159,115), radius=6, outline="white",width = 1) 


  # 
    draw.text((68,17), today_date(), font=fontC11, fill="#FFCC00")  
    draw.text((82,0), today_time(), font=fontC15, fill="#FFCC00")  
    draw.text((136, 17), today_week(), font=fontC11, fill="#FFCC00")      
    
    draw.text((19, 45), cpu_temp(), fill="white")                     

    draw.text(posndisk_f, disk_free('/'), font=fontC11, fill="white")  
    draw.text(posndisk_t, disk_total('/'), font=fontC11, fill="white") 

    draw.text(posnram_f, ram_free(), font=fontC10, fill="white")      
    draw.text(posnram_t, ram_total(), font=fontC10, fill="white")    
    # draw.text(posndisk_p, disk_perc('/'), font=fontC11, fill="white")

    draw.text((33, 115), network('wlan0'), font=fontC11, fill="#00CCFF")


 
    draw.rectangle((cL-2, cT-2, c0L+CpuW+2, c0T+CpuH+2),outline="white")   
    draw.rectangle((cL, cT, c0L+CpuW, c0T+CpuH),fill="black")             
    draw.rectangle((c1L-2, c1T-2, c1L+CpuW+2, c0T+CpuH+2),outline="white")  
    draw.rectangle((c1L, c1T, c1L+CpuW, c0T+CpuH),fill="black")
    draw.rectangle((c2L-2, c2T-2, c2L+CpuW+2, c0T+CpuH+2),outline="white")
    draw.rectangle((c2L, c2T, c2L+CpuW, c0T+CpuH),fill="black")    
    draw.rectangle((c3L-2, c3T-2, c3L+CpuW+2, c0T+CpuH+2),outline="white")
    draw.rectangle((c3L, c3T, c3L+CpuW, c0T+CpuH),fill="black")
    draw.rectangle((c4L-2, c4T-2, c4L+CpuW+2, c0T+CpuH+2),outline="white")
    draw.rectangle((c4L, c4T, c4L+CpuW, c0T+CpuH),fill="black")


    if c0BarH < CpuH:
            
        if  c0 < 30:
            draw.text(posncpu,  cpu(),  fill="#00FF00")
            draw.rectangle((cL, CpuB-c0BarH, c0L+CpuW, CpuB), fill="#99FF00")                      
            draw.rectangle((c1L, CpuB-c1BarH, c1L+CpuW, CpuB), fill="#99FF00")                      
            draw.rectangle((c2L, CpuB-c2BarH, c2L+CpuW, CpuB), fill="#99FF00")
            draw.rectangle((c3L, CpuB-c3BarH, c3L+CpuW, CpuB), fill="#99FF00")
            draw.rectangle((c4L, CpuB-c4BarH, c4L+CpuW, CpuB), fill="#99FF00")
        else:
            if  c0 < 50:
                draw.text(posncpu, cpu(),  fill="#FF6600")
                draw.rectangle((cL, CpuB-c0BarH, c0L+CpuW, CpuB), fill="#FF6600")                      
                draw.rectangle((c1L, CpuB-c1BarH, c1L+CpuW, CpuB), fill="#FF6600")
                draw.rectangle((c2L, CpuB-c2BarH, c2L+CpuW, CpuB), fill="#FF6600")
                draw.rectangle((c3L, CpuB-c3BarH, c3L+CpuW, CpuB), fill="#FF6600")
                draw.rectangle((c4L, CpuB-c4BarH, c4L+CpuW, CpuB), fill="#FF6600")
            else:
                draw.text(posncpu, cpu(),  fill="red")
                draw.rectangle((cL, CpuB-c0BarH, c0L+CpuW, CpuB), fill="red")    
                draw.rectangle((c1L, CpuB-c1BarH, c1L+CpuW, CpuB), fill="red")
                draw.rectangle((c2L, CpuB-c2BarH, c2L+CpuW, CpuB), fill="red")
                draw.rectangle((c3L, CpuB-c3BarH, c3L+CpuW, CpuB), fill="red")
                draw.rectangle((c4L, CpuB-c4BarH, c4L+CpuW, CpuB), fill="red")
    else:
        draw.rectangle((minCpuBarW, minCpuBarH, maxCpuBarW, maxCpuBarH), fill="red")

    draw.rectangle((dL-2, dT-2, dL+DiskW+2, dT+DiskH+2),outline="white")
    draw.rectangle((dL, dT, dL+DiskW, dT+DiskH),fill="black") 

    if dBarW < DiskW:
            
        if  diskPerc < 40:
            # draw.text(posncpu,  cpu(),  fill="#00FF00")
            draw.rectangle((dL, dT, dL+dBarW, dT+DiskH), fill="#99FF00")                      

        else:
            if  diskPerc < 80:
                # draw.text(posncpu, cpu(),  fill="#FF6600")
                draw.rectangle((dL, dT, dL+dBarW, dT+DiskH), fill="#FF6600")                      

            else:
                # draw.text(posncpu, cpu(),  fill="red")
                draw.rectangle((dL, dT, dL+dBarW, dT+DiskH), fill="red")    

    else:
        draw.rectangle((minCpuBarW, minCpuBarH, maxCpuBarW, maxCpuBarH), fill="red")



    draw.rectangle((rL-2, rT-2, rL+RamW+2, rT+RamH+2),outline="white")
    draw.rectangle((rL, rT, rL+RamW, rT+RamH),fill="black") 

    if rBarW < RamW:
            
        if  ramPerc < 40:
            # draw.text(posncpu,  cpu(),  fill="#00FF00")
            draw.rectangle((rL, rT, rL+rBarW, rT+RamH), fill="#99FF00")                      

        else:
            if  ramPerc < 80:
                # draw.text(posncpu, cpu(),  fill="#FF6600")
                draw.rectangle((rL, rT, rL+rBarW, rT+RamH), fill="#FF6600")                      

            else:
                # draw.text(posncpu, cpu(),  fill="red")
                draw.rectangle((rL, rT, rL+rBarW, rT+RamH), fill="red")    

    else:
        draw.rectangle((minCpuBarW, minCpuBarH, maxCpuBarW, maxCpuBarH), fill="red")
  #------------------------------------------------------------------------------------------





    # draw.bitmap((20, 60), newimg1, fill="green")
    # draw.bitmap((70, 60), newimg2, fill="red")
    device.display(bg)    
  


#==========================================================================================


if __name__ == "__main__":
    serial = spi(port=0, device=0, gpio_DC=23, gpio_RST=24)
    device = st7735(serial, rotate=2)
    
    while True:
        main()
        time.sleep(0.2)